package com.sky.controller.admin;


import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/admin/common")

/**
 * 通用控制器
 */
public class CommonController {

    //注入阿里云oss对象
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        //调用阿里云oss上传方法

        // 获取上传文件原始名称
        String originalFilename = file.getOriginalFilename();  // 获取上传文件原始名称
        log.info("文件原始名称:{}",originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));  //获取原始文件的后缀名
        String url = null;  // 上传到阿里云oss返回的文件访问路径
        try {
            String objectName = UUID.randomUUID().toString() + suffix;
             url = aliOssUtil.upload(file.getBytes(), objectName);
        } catch (IOException e) {
           log.info("文件上传失败!!!");
           return Result.error("文件上传失败");
        }

        return Result.success(url);
    }

}
